package developer.核心类.线程;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.TtlExecutors;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhangyongkang
 * @time 2025/8/7 14:48
 * @description
 */
public class ThreadLocalTest {
    private static final TransmittableThreadLocal<String> ttl = new TransmittableThreadLocal<>();

    public static void main(String[] args) {
        // 包装线程池，使其支持 TTL 传递
        ExecutorService executor = TtlExecutors.getTtlExecutorService(Executors.newFixedThreadPool(1));

        // 主线程设置值
        ttl.set("hello from main thread");

        // 提交任务到线程池
        executor.submit(() -> {
            // 工作线程中可以获取主线程的 TTL 值
            System.out.println("线程池任务获取值: " + ttl.get()); // 输出：hello from main thread
        });

        executor.shutdown();
        ttl.remove(); // 清理
    }
}
